<template>
    <div>
        <button type="button" @click="selectFile" class="btn btn-white btn-default btn-round">
            <i class="ace-icon fa fa-upload"></i>
            {{text}}
        </button>
        <br/>
        <input class="hidden" type="file" ref="file" v-bind:id="inputId+'-input'" v-on:change="uploadFile">
    </div>
</template>

<script>
  import axios from "axios";

  export default {
    name: 'oss-file',
    props: {
      text: {
        default: "上传文件"
      },
        afterUpload:{
            type: Function,
            default: null
        },
        inputId:{
          default: "file-upload"
        },
        suffixs:{
            default: []
        },
        use:{
          default:""
        }
    },
    data: function () {
      return {
      }
    },
    methods: {
        /*
              * 头像上传
              * */
         uploadFile(){
            //定义一个表单
            let formData=new window.FormData();
            //拿到file组件
            let file_info=this.$refs.file.files[0];
            //判断文件格式
            let suffixs=this.suffixs;
            let fileName=file_info.name;
            let suffix=fileName.substring(fileName.lastIndexOf(".")+1,fileName.length).toLowerCase();
            let validateSuffix=false;
            for(let i=0;i<suffixs.length;i++){
                if(suffixs[i].toLowerCase()===suffix){
                    validateSuffix=true;
                    break;
                }
            }

            if(!validateSuffix){
                Toast.warning("文件格式不正确!,只支持:"+suffixs.join(","));
                $('#'+this.inputId+"-input").val("");
                return;
            }

            //key: "file"必须和后端controller参数名一致。
            formData.append("file",file_info);
            formData.append("use",this.use);
            Loading.show();
            axios.post("/file/admin/oss-simple",formData).then((response)=>{
                Loading.hide();
                const data=response.data;
                if(data.success){
                    //调用暴露给外部的函数
                    this.afterUpload(data);
                    let image=data.content;
                    console.log("上传文件地址: ",image);
                    // teacherinfo.value.image=image;
                    //清空控件中的值
                    $('#'+this.inputId+"-input").val("");
                }
            })
        },

        /*
        * 触发上传按钮
        * */
        selectFile(){
            $('#'+this.inputId+"-input").trigger("click");
        }
    }
  }
</script>